package com.joolun.framework.aspectj;

import com.joolun.common.core.domain.AjaxResult;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@RestControllerAdvice
public class TimestampAdvice implements ResponseBodyAdvice<AjaxResult<?>> {

    @Override
    public boolean supports(MethodParameter returnType, 
                            Class<? extends HttpMessageConverter<?>> converterType) {
        // 只处理返回类型为 AjaxResult 的控制器方法
        return AjaxResult.class.isAssignableFrom(returnType.getParameterType());
    }

    @Override
    public AjaxResult<?> beforeBodyWrite(AjaxResult<?> body,
                                         MethodParameter returnType,
                                         MediaType selectedContentType,
                                         Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                         ServerHttpRequest request,
                                         ServerHttpResponse response) {
        // 为响应体添加时间戳
        if (body != null) {
            body.put(AjaxResult.TIME,System.currentTimeMillis());
        }
        return body;
    }
}